package org.belkodevelop.controller;

import org.belkodevelop.controller.helper.AuthUtils;
import org.belkodevelop.report.domen.PatientReport;
import org.belkodevelop.report.service.ReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("/report")
public class ReportController {

    private static String DATE_FORMAT = "DD.MM.YYYY";

    @Autowired
    private AuthUtils authUtils;

    @Autowired
    private ReportService reportService;

    @RequestMapping("/build")
    public ModelAndView buildReport(@RequestParam String dateStartReport,
                                    @RequestParam String dateEndReport,
                                    @RequestParam Integer patientId,
                                    HttpServletResponse response) throws IOException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
        Date dateStartReportDate;
        Date dateEndReportDate;
        try {
            dateStartReportDate = simpleDateFormat.parse(dateStartReport);
            dateEndReportDate = simpleDateFormat.parse(dateEndReport);
        } catch (ParseException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "parse date error");
            return null;
        }
        PatientReport patientReport = reportService.getPatientReport(patientId, authUtils.getCurrentUser(), dateStartReportDate, dateEndReportDate);
        return new ModelAndView("pdfPatientReportView", "patientReport", patientReport);
    }

}
